<?php

namespace App\Http\Middleware;

use Closure;

class CheckAdminLogin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(!auth()->check()){
            return redirect(route('admin.login'))->withErrors(['error'=>'请登录']);
        }
        // 访问的权限
        $authes = is_array(session('admin.auth')) ? array_filter(session('admin.auth')) : [];
        $authes = array_merge($authes,config('rbac.allow_route'));
        // 当前的路由
        $currentRoute = $request->route()->getName();
        if(auth()->user()->username != config('rbac.super') && !in_array($currentRoute,$authes)){
            return redirect(route('admin.403'));
        }
        //使用request来添加一个属性，传到下一级
        $request->authes = $authes; //相当于给对象加了一个属性
        
        // 没有停止则向后执行
        return $next($request);
    }
}
